package com.ftg.rbac.util;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * 对树形表进行处理的通用类
 *
 * @author kangjx
 * @version 1.0
 * @date 2023/3/20 上午8:26
 */
public class TreeUtil {

    /**
     * 通过过指定的值，查找子元素
     * @param parentIdName     上级的列名称
     * @param idName           主键的列名称
     * @param childrenName     生成子的时候，key名称 Ex : child:[]  children:[]  son:[] lists:[]
     * @param parent           当前节点
     * @param depts            结果集
     * @param <T>              T 实体
     * @param <E>              E 树形vo
     */
    @SuppressWarnings("unchecked")
    public static <T,E> void findChildren(String parentIdName,String idName,String childrenName,E parent,List<T> depts){

        assert  parent != null;
        assert  depts != null;

        String tempName = childrenName.substring(0,1).toUpperCase() + childrenName.substring(1) ;
        System.out.println(tempName);
        try {
            Method getChildrenMethod = parent.getClass().getMethod("get"+tempName);
            List<Object> childrenVal = (List<Object>) getChildrenMethod.invoke(parent);

            if(childrenVal == null){
                Method setChildrenMethod = parent.getClass().getMethod("set"+tempName,List.class);
                setChildrenMethod.invoke(parent,new ArrayList<>());
            }
            for (T dept : depts) {

                PropertyDescriptor getKey = new PropertyDescriptor(idName,parent.getClass());
                Method getKeyReadMethod = getKey.getReadMethod();
                Object getKeyVal = getKeyReadMethod.invoke(parent);

                PropertyDescriptor getParentId = new PropertyDescriptor(parentIdName,dept.getClass());
                Method getParentIdReadMethod = getParentId.getReadMethod();
                Object getParentIdVal = getParentIdReadMethod.invoke(dept);

                if(getKeyVal.equals(getParentIdVal)){
                    Object temp = parent.getClass().newInstance();
                    castClass(dept,temp);
                    depts.remove(dept);
                    List<Object> children = (List<Object>) getChildrenMethod.invoke(parent);
                    children.add(temp);
                    findChildren(parentIdName,idName,childrenName,temp,depts);
                }
            }

        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | IntrospectionException |
                 InstantiationException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 生成树的简化方法 默认编写  "superid","did","children",null
     * @param treeClass   返回类型
     * @param ds          结果集
     * @return            树
     * @param <T>          实体
     * @param <E>          树形vo
     */
    public static <T,E> E createTree(Class<E> treeClass,List<T> ds){
        return TreeUtil.createTree("superid","did","children", treeClass,ds,null);
    }

    /**
     *  生成树的核心方法
     * @param parentIdName     上级的列名称
     * @param idName           主键的列名称
     * @param childrenName     生成子的时候，key名称 Ex : child:[]  children:[]  son:[] lists:[]
     * @param treeClass        返回类型的关联对象
     * @param ds               结果集
     * @param <T>              T 实体
     * @param <E>              E 树形vo
     * @param rootVal       最大的上级编号的默认值  null
     * @return              树形结构
     */
    public static <T,E> E createTree(String parentIdName,String idName,String childrenName,Class<E> treeClass,List<T> ds,Integer rootVal){

        CopyOnWriteArrayList<T> depts = new CopyOnWriteArrayList<>(ds);

        E tree = null;
        try {
            tree = treeClass.newInstance();

            for (int i = 0; i < depts.size(); i++) {
                T t1 = depts.get(i);

                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(parentIdName,t1.getClass());
                Method parentGetMethod = propertyDescriptor.getReadMethod();

                Object parentIdVal = parentGetMethod.invoke(t1);

                boolean t = (parentIdVal == null && rootVal == null) || parentIdVal.equals(rootVal);
                if( t ){
                    castClass(depts.get(i),tree);
                    findChildren(parentIdName,idName,childrenName,tree,depts);
                }
            }

        } catch (InstantiationException | IllegalAccessException | IntrospectionException | InvocationTargetException e) {
            throw new RuntimeException(e);
        }

        return tree;
    }

    /**
     * 两个类的里面的属性值相互转换的过程
     * 约定一下，sourceClass targetClass属性相同的进行转换
     * @param sourceClass  源始数据对象
     * @param targetClass  目标对象
     *                     Dept d1 = new Dept();
     *                     castClass（d1）
     */
    public static Object castClass(Object sourceClass,Object targetClass){
        Class sClass = sourceClass.getClass();
        Class tClass = targetClass.getClass();

        Field[] sourceFields = sClass.getDeclaredFields();
        for (Field sourceField : sourceFields) {
            //取到sClass 类里面的  这个属性sourceField一对 set get
            try {
                // A PropertyDescriptor describes one property that a Java Bean exports via a pair of accessor methods.
                PropertyDescriptor sourcePropertyDescriptor = new PropertyDescriptor(sourceField.getName(),sClass);
                Method sourceGetMethod = sourcePropertyDescriptor.getReadMethod();

                PropertyDescriptor targetPropertyDescriptor = new PropertyDescriptor(sourceField.getName(),tClass);
                Method targetSetMethod = targetPropertyDescriptor.getWriteMethod();
                targetSetMethod.invoke(targetClass,sourceGetMethod.invoke(sourceClass));

            }catch (IllegalAccessException | InvocationTargetException | IntrospectionException e) {
                System.err.println("目标类里面没有与原始类里面相同的字段!!!");
            }
        }
        return targetClass;
    }

}
